<?php

namespace App\Http\Controllers\Admin\RandomCheck;

use App\Exceptions\LogicException;
use App\Http\Controllers\Controller;
use App\Models\Adminer\Admins;
use App\Models\RandomCheck\RandomCheckModule;
use App\Models\RandomCheck\RandomCheckPoint;
use App\Utils\QueryUtil;
use App\Utils\ResUtil;


class PointController extends Controller
{
    public function list()
    {
        $request = request()->all();
        $query = RandomCheckPoint::where(function($query) use($request) {
            QueryUtil::selectBuild($query, $request, [
                ['product_id', '='],
                ['module_id', '='],
                ['point', 'like', 'point'],
                ['point_remark', 'like', 'point_remark'],
                ['created_adminer', 'like', 'created_adminer'],
                ['updated_adminer', 'like', 'updated_adminer'],
                ['adminer', 'like', 'adminer'],
                ['id', '='],
            ]);
        });

        $total = $query->count();
        $models = QueryUtil::queryList($query);
        $list = [];
        foreach($models as $i => $v) {
            $list[$i] = $v?->label()?->toArray();
        }
        $hasMore = QueryUtil::hasMore(sizeof($list));
        return $this->ok(compact('list', 'total', 'hasMore'));
    }

    public function edit()
    {
        $data = request()->all();
        $rule = [
            'id' => '',
            'module_id' => 'required',
            'point' => 'string|required',
            'point_remark' => 'string|required',
            'adminer' => '',
        ];
        $validator = validatorService()->checkValidator($rule, $data, RandomCheckPoint::$fillables);
        if ($validator['code'] != 200) {
            throw new LogicException($validator['data']);
        }

        if($data['id'] ?? '') {
            $project = RandomCheckPoint::find($data['id']);
            if(!$project) {
                throw new LogicException(ResUtil::NOT_DATA);
            }
        } else {
            $project = new RandomCheckPoint();
            $project->created_adminer = Admins::getInfoById($this->authAdmin()->id);
        }
        $module = RandomCheckModule::find($data['module_id']);
        if(!$module) {
            throw new LogicException('模块不存在');
        }

        $project->fill([
            'product_id' => $module->product_id,
            'point_remark' => $data['point_remark'],
            'module_id' => $module->id,
            'point' => $data['point'],
            'adminer' => $data['adminer'] ?? $module->adminer,
            'updated_adminer' => Admins::getInfoById($this->authAdmin()->id)
        ]);
        $project->save();
        return $this->ok();
    }
}
